package com.laivi.basic.model.sql;

import java.util.HashMap;
import java.util.Map;

public class Join {
	private StringBuffer join;
	
	private StringBuffer where;
	
	private int index=0;
	
	private Map<String,String>tableMap=new HashMap<String,String>();
	
	public static Join create(String...fields){
		return new Join().field(fields);
	}
	
	private Join field(String...fields){
		join=new StringBuffer("select ");
		if(fields!=null && fields.length!=0){
			for(int i=0;i<fields.length;i++){
				join.append(fields[i]+",");
			}
			join=new StringBuffer(join.substring(0, join.length()-1));
			join.append(" ");
		}else{
			join.append("*");
		}
		return this;
	}
	
	public Join table(String...tables){
		join.append(" from ");
		for(int i=0;i<tables.length;i++){
			join.append(tables[i]+" t"+(i+1)+",");
			tableMap.put(tables[i], "t"+(++index));
		}
		join=new StringBuffer(join.substring(0, join.length()-1));
		join.append(" ");
		return this;
	}
	
	public Join left(String table1,String table2,String field1,String field2){
		if(join.indexOf(" from ")==-1){
			tableMap.put(table1, "t"+(++index));
			join.append(" from "+table1+" "+tableMap.get(table1));
		}
		tableMap.put(table2, "t"+(++index));
		join.append(" left join "+table2+" "+tableMap.get(table2)+" on "+tableMap.get(table1)+"."+field1+"="+tableMap.get(table2)+"."+field2);
		return this;
	}
	
	public Join where(String table1,String table2,String field1,String field2){
		if(where!=null && where.length()>0){
			where.append(" and "+tableMap.get(table1)+"."+field1+"="+tableMap.get(table2)+"."+field2);
		}else{
			where.append(tableMap.get(table1)+"."+field1+"="+tableMap.get(table2)+"."+field2);
		}
		return this;
	}
	
	public String toJoin(){
		if(join!=null){
			return join.toString();
		}
		return null;
	}
	
	public String toWhere(){
		if(where!=null){
			return where.toString();
		}
		return null;
	}
	
}
